<template>
  <a-modal v-model:visible="visible" :title="form.id ? '编辑爬取来源' : '新建爬取来源'" :on-before-ok="confirm">
    <a-row justify="center">
      <a-form ref="formRef" :model="form" size="medium" auto-label-width :style="{ width: 'auto' }">
        <a-form-item field="name" label="爬取来源" :rules="rules.name">
          <a-input v-model="form.name" placeholder="请输入爬取来源" style="width: 300px" />
        </a-form-item>
        <a-form-item field="url" label="URL" :rules="rules.url">
          <a-input v-model="form.url" placeholder="请输入URL" style="width: 300px" />
        </a-form-item>
      </a-form>
    </a-row>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { Message, Modal, type FormInstance } from '@arco-design/web-vue'
import { IconEdit, IconPlus } from '@arco-design/web-vue/es/icon'
import { addScrapySource, scrapySourceDetail, scrapySourceEdit } from '@/apis'

type Form = { name: string; url: string; id?: string }
const form: Form = reactive({
  name: '',
  url: '',
  id: ''
})

const emits = defineEmits(['reFreshTable'])
const rules = {
  url: [{ required: true, message: '请输入URL' }],
  name: [{ required: true, message: '请输入爬取来源' }]
}

const visible = ref(false)
const detailId = ref('')
const formRef = ref<FormInstance>()

const confirm = async () => {
  const flag = await formRef.value?.validate()
  if (flag) {
    return false
  } else {
    let resData = {}
    if (form.id) {
      resData = await scrapySourceEdit({
        ...form,
        site_id: form.id
      })
    } else {
      resData = await addScrapySource({
        ...form
      })
    }
    if (resData.code === 1) {
      Message.success(resData.msg)
      visible.value = false
      form.id = ''
      form.name = ''
      form.url = ''
      emits('reFreshTable')
    } else {
      Message.error(resData.msg)
      return false
    }
  }
}

const show = (id: string) => {
  form.id = id
  visible.value = true
  id && initScrapySource(id)
}
const initScrapySource = async (id) => {
  const res = await scrapySourceDetail({ site_id: id })

  let resData = res.data || {}
  if (res.code === 1) {
    form.name = resData.name
    form.url = resData.url
  } else {
    Message.error(resData.message)
  }
}
defineExpose({ show })
</script>

<style lang="scss" scoped>
:deep(.arco-collapse-item-content) {
  background: none;
}
</style>
